package systems;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import entities.Author;

public class RecentlyAuthorUpdate {
	
	private static String cacheName = "recentlyAuthorUpdate";
	
	private static int limit = 50;
	
	public static void insert(Author author) {
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   e1.printStackTrace();
		}
		
		List<Author> authors = new ArrayList<Author>();
		if(cache!=null&&cache.containsKey(cacheName))
		{
			authors = (List<Author>) cache.get(cacheName);
		}
		
		for (int i = 0; i < authors.size(); i++) {
			if (authors.get(i).getId().equals(author.getId())) {
				authors.remove(authors.get(i));
			}
		}
		
		if (authors.size() >= limit) {
			authors.remove(limit - 1);
		}
		
		authors.add(0, author);
		
		cache.put(cacheName, authors);
	}
	
	public static List<Author> getAuthors() {
		List<Author> authors = new ArrayList<Author>();
		
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   //e1.printStackTrace();
		}
		
		if(cache!=null&&cache.containsKey(cacheName))
		{
			authors = (List<Author>) cache.get(cacheName);
		}
		
		return authors;
	}
}
